/*
    Nombre de la clase: Ann_Tsk_Std_Cntlr
    Autor: Elias Almanza Laguna
    Objetivo de la clase: Proporcionar los metodos relacionados
                            con el manejo de información de las
                            tareas en el portal del usuario estandar
                            (Recursos Humanos). En el portal del
                            usuario estandar se pueden ver y modificar
                            todas las tareas de todos los empleados.
    */
    
public class Ann_Tsk_Std_Cntlr {


/*********** VARIABLES BEGIN ************/
    public Boolean disable_Edit_Ann{get;set;}
    public Boolean disable_Edit_Atask{get;set;}
    public Boolean isNewAtask{get;set;}
    
    public Announcement__c Announcement_parent{get;set;}
    
    private Ann_Tsk_Std_Cntlr stdCtrl {get; set;} 
    public String Ann_Id{get;set;}
    private Id accountId;
    public String filtro {get;set;}
    public Date Date1 {get;set;}
    public Date Date2 {get;set;}
    public String Date1str {get;set;}
    public String Date2str {get;set;}
    public String tempPageRef {get; set;}
    public String Atask_Id{get;set;}
    public String AtaskUser_Id{get;set;}
    public List<A_Task__c> Atask_edit{get; set;}
    public List< A_Task_User__c> a_task_users_list{get; set;}  
    
    public A_Task__c Atask_New;
    public A_Task__c getAtask_New(){
        if(Atask_New==null)
        Atask_New = new A_Task__c();
        return Atask_New;
    }
    
    public A_Task_User__c AtaskUser_New;
    public A_Task_User__c getAtaskUser_New(){
        if(AtaskUser_New==null)
        AtaskUser_New = new A_Task_User__c();
        return AtaskUser_New;
    }
    
    private Id myUserId;
    private List<A_Task_User__c> tsk_u;
    private List<Id> ids;
    public List<A_Task__c> results{get;set;}
    
    
     public Field_Container__c getfieldContainer(){
        if(fieldContainer==null)
        fieldContainer = new Field_Container__c();
        return fieldContainer;
    }
    
    public Field_Container__c fieldContainer{get;set;}
    public String message {get;set;}
    
   
/*********** VARIABLES END ************/

/*********** FUNCTIONS BEGIN ************/


    /*
     *** Constructor de la clase ***
       - Se asigna el filtro a "All" para desplegar todas
            las tareas sin importar el estatus de la tarea.
       - Se inicializa el dato booleano 'isNewAtask' con el
            valor 'falso' ya que consideramos en un principio
            que no habrá nueva tarea sino hasta que revisemos
            si existen parámetros en la pagina actual.
       - Se hace una verificación de parámetros de la página
            actual.
       - Creamos la instancia de 'fieldContainer' el cual es
            un objeto del que usamos 2 campos tipo Date para
            un filtro de fechas en el despliegue de la lista
            de tareas.
    */
    public Ann_Tsk_Std_Cntlr(){
            isNewAtask = false;
            filtro = 'All';
            verifyParameters();
            fieldContainer=new Field_Container__c();
    }
    
    /*
    *** Method geta_tasks() ***
    - Objetivo: Método para realizar una consulta del objeto A_Task__c,
               es decir, las tareas. La consulta tiene un filtro del
               estatus de la tarea y un filtro de rango de fechas. La
               consulta se guarda en el objeto 'results'.
    */
    public void geta_tasks(){
        tsk_u = new List<A_Task_User__c>();
        tsk_u = [SELECT A_Task_User__c.Name, A_Task_User__c.Announcement_Task__c  FROM A_Task_User__c ];
        ids = new List<Id>();
        for(A_Task_User__c t_u : tsk_u){    
            ids.add(t_u.Announcement_Task__c);
        }          
                 
        if (filtro == 'All') {
            results = [SELECT Id, Name, Status__c, Due_Date__c FROM A_Task__c WHERE (A_Task__c.Id IN :ids) AND ( Due_Date__c>=:fieldContainer.Start_Date__c AND Due_Date__c<=:fieldContainer.End_Date__c ) ];
        } else {
            results = [SELECT Id, Name, Status__c, Due_Date__c FROM A_Task__c WHERE (A_Task__c.Id IN :ids) AND (Status__c=:filtro) AND ( Due_Date__c>=:fieldContainer.Start_Date__c AND Due_Date__c<=:fieldContainer.End_Date__c ) ];
        }   

    }
    
   
    /*
    *** Method processRequests() ***
    - Objetivo: Método para realizar una consulta del objeto A_Task__c,
               es decir, las tareas. La consulta se guarda en el objeto
               'results'. Este metodo tiene la misma función que 
               'geta_tasks()' pero 'processRequests()' se ejecuta cuando
               se realiza un cambio en el filtro de estatus o en el rango
               de fechas, o bien, cuando se realiza la modificación de un
               registro de tareas.
    */ 
    public PageReference processRequests(){
        tsk_u = new List<A_Task_User__c>();
        tsk_u = [SELECT A_Task_User__c.Name, A_Task_User__c.Announcement_Task__c  FROM A_Task_User__c ];
        ids = new List<Id>();
        for(A_Task_User__c t_u : tsk_u){    
            ids.add(t_u.Announcement_Task__c);
        }             
        if (filtro == 'All') {
            results = [SELECT Id, Name, Status__c, Due_Date__c,Description__c, URL__c FROM A_Task__c WHERE   ( Due_Date__c>=:fieldContainer.Start_Date__c AND Due_Date__c<=:fieldContainer.End_Date__c ) ];
        } else {
            results = [SELECT Id, Name, Status__c, Due_Date__c,Description__c, URL__c FROM A_Task__c WHERE (Status__c=:filtro) AND   ( Due_Date__c>=:fieldContainer.Start_Date__c AND Due_Date__c<=:fieldContainer.End_Date__c ) ];
        }   
        return null;
    }
    
  
  public PageReference Atask_std_Open() {
    tempPageRef = 'Atask_std_Edit';
        return null;
    }
    
    public PageReference AtaskUser_Open() {
     tempPageRef = 'AtaskUser_Edit';
        return null;
    }

    
    public PageReference Atask_std_New() {
        tempPageRef = 'Atask_std_New_Edit_Ann';
        isNewAtask = true;
        return null;
    }
    
    public PageReference Ataskuser_New() {
        Atask_New = [SELECT Id, Name FROM A_Task__c WHERE Id= :Atask_Id];
        tempPageRef = 'AtaskUser_New';
        return null;
    }

      
     public PageReference save_new_task() {
       IF (Atask_New!=null){
           Atask_New.Announcement__c = Ann_Id;
           insert Atask_New;
           Atask_Id=Atask_New.Id;
           isNewAtask = false;
           tempPageRef = 'Atask_std_Edit';
       }
       return null;
    }
    
    public PageReference save_new_task_edit_ann() {
       
       IF (Atask_New!=null){
           insert Atask_New;
            PageReference redirect = new PageReference('/apex/Announcements');     
            redirect.getParameters().put('paramAnn_id',Ann_Id); 
            redirect.setRedirect(true); 
            return redirect;
       } else {
                PageReference redirect = new PageReference('/apex/Announcements'); 
                redirect.getParameters().put('paramAnn_id',Ann_Id); 
                redirect.setRedirect(true); 
                return redirect;
       }
    }
    
     public PageReference save_new_taskuser() {
       IF (AtaskUser_New!=null){
           AtaskUser_New.Announcement_Task__c = Atask_New.Id;
           try {
               insert AtaskUser_New;
               Atask_Id=AtaskUser_New.Announcement_Task__c;
           AtaskUser_Id = AtaskUser_New.Id;
           AtaskUser_New =null;
           //tempPageRef = 'Atask_std_Edit';
            //message = 'Hoooola';
           PageReference redirect = new PageReference('/apex/AnnouncementTasks'); 
        redirect.getParameters().put('paramAtask_Id',Atask_Id); 
        redirect.setRedirect(true); 
        return redirect; 
           }
           catch(System.DmlException ex){
                //ApexPages.addMessages(ex);
                
               //ApexPages.Message dupeMsg = new ApexPages.Message(ApexPages.Severity.ERROR,
               //  'Error: ' + ex);
               // ApexPages.addMessage(dupeMsg);
               //message = 'Whoops! An error occurred -- ' + ex.getMessage();   
               //message = 'Whoops! An error occurred -- '+ex.getMessage();
               message = 'The user trying to add is already associated with the task. Please choose another user.';
                               
                //drawError = true;
                //ApexPages.addMessage(new ApexPages.Message(ApexPages.severity.ERROR,'User already exists in this task'));
                //ApexPages.addmessage(new ApexPages.message(ApexPages.severity.WARNING,'User already exists in this task'));
        //return null;   
           }
           
           
       }
       return null;
    }
  
   public PageReference openAtask() {
        Atask_edit = [SELECT Id, Name, Due_Date__c,Status__c, Description__c,URL__c FROM A_Task__c WHERE Id=:Atask_Id LIMIT 1];  
        Set<Id> ids_atask = new Set<Id>();
        for(A_Task__c a_task : Atask_edit){    
            ids_atask.add(a_task.Id); 
            }
        a_task_users_list = [SELECT Name,User__c, User__r.name FROM A_Task_User__c WHERE Announcement_Task__c IN :ids_atask ];
        return null;
    }
    
   
   public PageReference verifyParameters() {
       tempPageRef = 'Ann_Task_List';
         if (ApexPages.currentPage().getParameters().containsKey('paramAnn_Id')){
               system.debug('verifyparamaters_if_paramAnn_Id');
               Ann_Id = ApexPages.currentPage().getParameters().get('paramAnn_Id');
               Announcement_parent = [SELECT Name, Id FROM Announcement__c WHERE Id=:Ann_Id];
               system.debug(Announcement_parent);
               tempPageRef = 'Atask_std_New';           
         }
         else{
               if (ApexPages.currentPage().getParameters().containsKey('paramAtask_Id')){
                   Atask_Id = ApexPages.currentPage().getParameters().get('paramAtask_Id');
                   tempPageRef = 'Atask_std_Edit';
               } else{
                        if (isNewAtask==true){
                                                system.debug('verifyparamaters_if_isNewAtask==true');
                                                
                                                tempPageRef = 'Atask_std_New_Edit_Ann';
                                                system.debug(isNewAtask);
                                                isNewAtask=false;
                                                }
                        else {system.debug(isNewAtask);
                 
                             }
                      }
           }
        return null;
    }


    public PageReference save_atask() {
       IF (Atask_edit!=null){
           update Atask_edit;
       }
       tempPageRef = 'Ann_Task_List';
       return null;
    }


   
    public PageReference gotoTasks() {
            PageReference redirect = new PageReference('/apex/AnnouncementTasks'); 
            redirect.setRedirect(true); 
            return redirect;
    }
    
    public PageReference gotoTask_Edit() {
        tempPageRef = 'Atask_std_Edit';
        return null;
    }
    
    public PageReference gotoAnnouncement() {
        PageReference redirect = new PageReference('/apex/Announcements'); 
        redirect.getParameters().put('paramAnn_id',Ann_Id); 
        redirect.setRedirect(true); 
        return redirect;
    }
    
    public PageReference AtaskUser_Delete() {
        A_Task_User__c Atask_usr_del = new A_Task_User__c();
        Atask_usr_del= [SELECT id,name FROM A_Task_User__c WHERE Id=:AtaskUser_Id];
        delete Atask_usr_del;
        PageReference redirect = new PageReference('/apex/AnnouncementTasks'); 
        redirect.getParameters().put('paramAtask_Id',Atask_Id); 
        redirect.setRedirect(true); 
        return redirect; 
    }

   public PageReference save() {
       IF (results!=null){
           update results;
       }
      return null;
    }
    public PageReference cancel() {
        tempPageRef = 'Ann_Task_List';
        return null;
    }
    
    
    /*********** FUNCTIONS END ************/

}